import { PaginatorPlugin } from "@datorama/akita";
import { filter, switchMap } from "rxjs/operators";

import { AudiencesQuery, AudiencesStore, makeStore, AudienceEntity } from "@/state/audienceEntity/store";
import { AuthQuery, makeStore as makeAuthStore } from "@/state/auth/store";
import { RoomQuery, makeStore as makeRoomStore } from "@/state/room/store"

import roomService from "@/services/roomService";
import { ROOM_STATUS } from "@/constants/room";

export class AudiencesFacade {
  constructor(private roomId: string, private store: AudiencesStore, private query: AudiencesQuery, public paginator: PaginatorPlugin<AudienceEntity>, private authQuery: AuthQuery, private roomQuery: RoomQuery) {
  }
  pagination$ = this.paginator.pageChanges.pipe(
    filter(num => {
      const isAssistant = this.roomQuery.assistants.some(item => !!this.authQuery.userId && item.userId === this.authQuery.userId);
      return !!this.authQuery.userId && this.roomQuery.status === ROOM_STATUS.STARTED && (this.authQuery.userId === this.roomQuery.ownerId || this.authQuery.userId === this.roomQuery.anchorId || isAssistant);
    }),
    switchMap((pageNum) => {
      const ui = this.query.UI
      const reqFn = () => roomService.getSearchListSvc(this.roomId, pageNum, 10, ui.searchKey);
      return this.paginator.getPage(reqFn);
    }),
  )

  updateUI = (searchKey: string) => {
    this.store.updateUI(searchKey);
  }

  //重新发起查询并获取第一页结果
  doSearch = () => {
    // console.log('是否触发搜索');
    // this.paginator.setFirstPage();
    this.paginator.refreshCurrentPage()
  }

  prevPage = () => {
    this.paginator.prevPage();
  }

  nextPage = () => {
    this.paginator.nextPage();
  }

  //销毁store实例，释放内存
  destroy = () => {
    this.paginator.destroy();
    this.store.destroy();
  }
}

export const makeFacade = (roomId: string): AudiencesFacade => {
  const [store, query, paginator] = makeStore();
  const [, authQuery] = makeAuthStore();
  const [, roomQuery] = makeRoomStore();

  return new AudiencesFacade(roomId, store, query, paginator, authQuery, roomQuery);
}